from urllib.parse import urlparse, urlsplit, urldefrag, \
    urlencode, parse_qs, parse_qsl

print('urlparse urlparseattrs')
url = 'http://username:passwd@lavenliu.cn:80/path1;param1?name=laven&age=23#frag'
parsed = urlparse(url)
print(parsed)
print(parsed._fields)
print('scheme  :', parsed.scheme)
print('netloc  :', parsed.netloc)
print('path    :', parsed.path)
print('params  :', parsed.params)
print('query   :', parsed.query)
print('fragment:', parsed.fragment)
print('username:', parsed.username)
print('password:', parsed.password)
print('hostname:', parsed.hostname)
print('port    :', parsed.port)  # None if not specified

print('urlparse urlsplit')
url = 'http://username:passwd@lavenliu.cn:80/path1;param1/path2;param2?name=laven&age=23#frag'
parsed = urlsplit(url)
print(parsed)
print('scheme  :', parsed.scheme)
print('netloc  :', parsed.netloc)
print('path    :', parsed.path)
print('query   :', parsed.query)
print('fragment:', parsed.fragment)
print('username:', parsed.username)
print('password:', parsed.password)
print('hostname:', parsed.hostname)
print('port    :', parsed.port)

print()
print('urlparse urldefrags')
o_url = 'http://lavenliu.cn/path1;param1/path2;param2?name=laven&age=23#frag'
print('original:', o_url)
d = urldefrag(o_url)
print('url     :', d.url)
print('fragment:', d.fragment)

print()
print('urlparse geturl')
print(parsed.geturl())

print()
print('Encoding Query Arguments')
query_args = {
    'q': 'query string',
    'foo': 'bar',
}
encoded_args = urlencode(query_args)
print('Encoded:', encoded_args)

query_args = {
    'foo': ['foo1', 'foo2'],
}
print('Single  :', urlencode(query_args))
print('Sequence:', urlencode(query_args, doseq=True))

print()
print('Decode the query string')
encoded = 'foo=foo1&foo=foo2'

print('parse_qs :', parse_qs(encoded))
print('parse_qsl:', parse_qsl(encoded))
